package com.hmdp.config;

import cn.hutool.core.lang.Snowflake;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

/**
 * @create: 2022-03-10 19:05
 * @author: lazy-baby
 * @description:
 **/

@Component
public class RedisIdGenerator {

    public static final long BEGIN = 1646870400L;

    private final StringRedisTemplate redisTemplate;

    public RedisIdGenerator(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    public  long nextId(String keyPrefix) {

        //1.生成时间戳
        LocalDateTime now = LocalDateTime.now();
        long nowSecond = now.toEpochSecond(ZoneOffset.UTC);
        long ts = nowSecond - BEGIN;
        //2.生成序列号
        String toDay = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        String key = "incr:" + keyPrefix + toDay;
        long increment = redisTemplate.opsForValue().increment(key);
        return ts << 32 | increment;
    }

    public static void main(String[] args) {
        Snowflake snowflake = new Snowflake();
        long id = snowflake.nextId();
        System.out.println(id);
    }
}
